package com.oracle.springbootjpa.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.oracle.springbootjpa.componts.R;
import com.oracle.springbootjpa.util.JWTUtils;
import com.oracle.springbootjpa.util.JwtUtil;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor{

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //设置编码集格式
        request.setCharacterEncoding("utf-8");
        //获取请求头中的token
        String token = request.getHeader("Authorization");

        //大忌：不能让log中出现大量的异常信息
        if(ObjectUtils.isEmpty(token)){

            R result = new R(401,"token失效");
            String json = new ObjectMapper().writeValueAsString(result);
            response.getWriter().print(json);

            return false;
        }

        //校验token
        boolean b = JwtUtil.checkToken(token);
        System.out.println("b : " + b);
        if(b){
            return true;
        }

        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
